#include "hashTable.h"

static int NextPrime(int Num)
{
    return Num;
}

#define MinTableSize 7
HashTable InitializeTable(int TableSize)
{
    HashTable H;
    int i;
    if (TableSize < MinTableSize)
    {
        printf("Table size too small\n");
        return NULL;
    }

    H = malloc(sizeof(struct HashTbl));
    if (H == NULL)
    {
        printf("malloc error\n");
        goto _error;
    }

    //alloc list arrary
    H->TableSize = NextPrime(TableSize);
    H->TheLists = malloc(H->TableSize * sizeof(List));
    if (H->TheLists == NULL)
    {
        printf("malloc error\n");
        goto _error;
    }

    //alloc headers
    for (i = 0; i < H->TableSize; i++)
    {
        H->TheLists[i] = malloc(sizeof(struct ListNode));
        if (H->TheLists[i] == NULL)
        {
            printf("malloc error\n");
            goto _error;
        }
        else
        {
            H->TheLists[i]->Next = NULL;
        }
    }
    goto _exit;
_error:
    if (H != NULL)
    {
        free(H);
        if (H->TheLists != NULL)
        {
            free(H->TheLists);
        }
        for (i = 0; i < H->TableSize; i++)
        {
            if (H->TheLists[i] != NULL)
            {
                free(H->TheLists[i]);
            }
        }
        H = NULL;
    }
    goto _exit;
_exit:
    return H;
}

#define TRUE 1
#define FALSE 0
#define BOOL int

static BOOL Equal(ElementType Key1, ElementType Key2)
{
    if (Key1 == Key2)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

Position Find(ElementType Key, HashTable H)
{
    Position P;
    List L;
    L = H->TheLists[Hash(Key, H->TableSize)];
    P = L->Next;
    while (P != NULL && Equal(Key, P->Element))
    {
        P = P->Next;
    }
    return P;
}
void Insert(ElementType Key, HashTable H)
{
    Position Pos, NewCell;
    List L;
    //Find中重复计算了一次Hash，待修改
    Pos = Find(Key, H);
    if (Pos == NULL)
    {
        NewCell = malloc(sizeof(struct ListNode));
        if (NewCell == NULL)
        {
            printf("malloc error\n");
        }
        else
        {
            L = H->TheLists[Hash(Key, H->TableSize)];
            NewCell->Next = L->Next;
            NewCell->Element = Key;
            L->Next = NewCell;
        }
    }
}